<?php

namespace app\company\controller;

use app\common\model\Supplier as SupplierModel;
use app\common\controller\CompanyController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="供应商管理")
 */
class Supplier extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SupplierModel();
        $this->each  = true;
        $this->sort  = ['sort' => 'desc', 'id' => 'desc'];
    }

    /**
     * @NodeAnnotation (title="新增")
     */
    public function add(Request $request): Json
    {
        try {
            $this->checkPost();
            $post = $request->post();
            $rule = [
                    'name|供应商名称'       => 'require|max:100|unique:dealer,name,company_id^delete_time',
                    'contact|联系人'        => 'require|max:100',
                    'phone|手机号'          => 'require|max:11',
                    'address|地址'          => 'require|max:100',
            ];
            $this->validate($post, $rule);
            $post['company_id'] = $this->companyId;
            $post['no']         = generateOrderNo('GYS');
            $this->model->transaction(function () use ($post, &$save)
            {
                $save = $this->model->save($post);
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }

    public function each($list)
    {
        return $list->each(function ($item)
        {
            $item->dealer_name = $item->dealer()->value('name');
        });
    }
}